package com.freeLearning.boot.shared.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.freeLearning.boot.common.enums.LogModuleEnum;
import com.freeLearning.boot.common.exception.BusinessException;
import com.freeLearning.boot.common.result.Result;
import com.freeLearning.boot.shared.auth.model.RefreshTokenRequest;
import com.freeLearning.boot.shared.auth.service.AuthService;
import com.freeLearning.boot.shared.auth.model.CaptchaResponse;
import com.freeLearning.boot.shared.auth.model.AuthTokenResponse;
import com.freeLearning.boot.common.annotation.Log;
import com.freeLearning.boot.system.model.entity.User;
import com.freeLearning.boot.system.model.entity.UserRole;
import com.freeLearning.boot.system.service.UserRoleService;
import com.freeLearning.boot.system.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 认证控制层
 *
 * @author Ray.Hao
 * @since 2022/10/16
 */
@Tag(name = "01.认证中心")
@RestController
@RequestMapping("/api/v1/auth")
@RequiredArgsConstructor
@Slf4j
public class AuthController {

    private final AuthService authService;
    private final UserService userService;
    private final UserRoleService userRoleService;
    private final List<Long> backRoleIds = List.of(1L,2L,13L);

    @Operation(summary = "登录")
    @PostMapping("/login")
    @Log(value = "登录", module = LogModuleEnum.LOGIN)
    public Result<AuthTokenResponse> login(
            @Parameter(description = "用户名", example = "admin") @RequestParam String username,
            @Parameter(description = "密码", example = "123456") @RequestParam String password,
            @RequestParam(required = false,defaultValue = "false") Boolean isBackLogin
    ) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        User user = userService.getOne(wrapper.eq("username", username));

        if (user != null && user.getStatus().equals(0)){
            return Result.failed("用户已经被禁用！");
        }
        if (user != null && isBackLogin) {
            UserRole one = userRoleService.getOne(new LambdaQueryWrapper<UserRole>()
                    .eq(UserRole::getUserId, user.getId())
                    .in(UserRole::getRoleId, backRoleIds)
            );
            if (one == null){
                return Result.failed("您没有注册为咨询师，无法登录后台！");
            }
        }
        AuthTokenResponse authTokenResponse = authService.login(username, password);
        return Result.success(authTokenResponse);
    }
    @Operation(summary = "注销")
    @DeleteMapping("/logout")
    @Log(value = "注销", module = LogModuleEnum.LOGIN)
    public Result<?> logout() {
        authService.logout();
        return Result.success();
    }

    @Operation(summary = "获取验证码")
    @GetMapping("/captcha")
    public Result<CaptchaResponse> getCaptcha() {
        CaptchaResponse captcha = authService.getCaptcha();
        return Result.success(captcha);
    }

    @Operation(summary = "刷新token")
    @PostMapping("/refresh-token")
    public Result<?> refreshToken(@RequestBody RefreshTokenRequest request) {
        AuthTokenResponse authTokenResponse = authService.refreshToken(request);
        return Result.success(authTokenResponse);
    }

    @Operation(summary = "微信登录")
    @PostMapping("/wechat-login")
    @Log(value = "微信登录", module = LogModuleEnum.LOGIN)
    public Result<AuthTokenResponse> wechatLogin(
            @Parameter(description = "微信授权码", example = "code") @RequestParam String code
    ) {
        AuthTokenResponse loginResult = authService.wechatLogin(code);
        return Result.success(loginResult);
    }
}
